using System;
using System.Reflection;
using Com.Core.Module.Abstractions;

namespace Com.Core.Module.Implementations;

public static class ModuleExtensions
{
    // 注册模块服务
    public static IServiceCollection AddApplicationModules(this IServiceCollection services, IConfiguration configuration)
    {
        var modules = DiscoverModules();
        foreach (var module in modules)
        {
            module.ConfigureServices(services, configuration);
        }
        return services;
    }

    // 配置模块中间件
    public static IApplicationBuilder UseApplicationModules(this IApplicationBuilder app)
    {
        var modules = DiscoverModules();
        foreach (var module in modules)
        {
            module.Configure(app);
        }
        return app;
    }

    private static IEnumerable<IModule> DiscoverModules()
    {
        return Assembly.GetExecutingAssembly()
            .GetTypes()
            .Where(t => typeof(IModule).IsAssignableFrom(t) && !t.IsInterface)
            .Select(Activator.CreateInstance)
            .Cast<IModule>();
    }
}
